package com.example.demo.controller;

/**
 * @author qinbo
 * @version 1.0
 * @description: TODO
 * @date 2025/2/11 22:47
 */

import com.example.demo.service.OcrService;
import com.example.demo.utils.ImageString;
import com.example.demo.utils.Result;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class OcrController {
    private final OcrService ocrService;

    public OcrController(OcrService ocrService) {
        this.ocrService = ocrService;
    }

//    @PostMapping("/ingredient/upload")
//    public ResponseEntity<String> generalBasicOcr(@RequestParam("image") MultipartFile image) {
//        try {
//            String result = ocrService.generalBasic(image.getBytes());
//
//            return ResponseEntity.ok(result);
//        } catch (Exception e) {
//            return ResponseEntity.internalServerError().body(e.getMessage());
//        }
//    }

    @PostMapping("/ingredient/upload")
    public Result generalBasicOcr(@RequestParam("image") MultipartFile image) {
        try {
            String result = ocrService.generalBasic(image.getBytes());
            // 解析JSON字符串
            JSONObject json = new JSONObject(result);
            JSONArray wordsResult = json.getJSONArray("words_result");

            StringBuilder result1 = new StringBuilder();

            // 遍历words_result数组，提取words字段的内容
            for (int i = 0; i < wordsResult.length(); i++) {
                JSONObject item = wordsResult.getJSONObject(i);
                String words = item.getString("words");
                result1.append(words).append(" ");
            }
            System.out.println(result1.toString().trim());
            ImageString imageString = new ImageString();
            imageString.setImageString(result1.toString().trim());
            return Result.success(200,"图片上传成功",result1.toString().trim());
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
